package com.cloud.drore.eboss.login;

import com.alibaba.fastjson.JSONObject;
import com.cloud.drore.eboos.common.base.Dictionary;
import com.cloud.drore.eboos.common.base.ResultMessage;
import com.cloud.drore.eboos.common.constant.CommonConstant;
import com.cloud.drore.eboos.common.constant.ResultCodeConstant;
import com.cloud.drore.eboos.common.entity.base.UserInfo;
import com.cloud.drore.eboos.common.util.LocalData;
import com.cloud.drore.eboos.exception.BusinessException;
import com.cloud.drore.eboss.login.feign.ILoginFeign;
import com.cloud.drore.eboss.login.feign.PasswordReset;
import com.cloud.drore.eboss.login.feign.ShiroUser;
import com.cloud.drore.eboss.login.feign.ShiroUserVo;
import com.cloud.drore.eboss.login.token.TokenManager;
import com.cloud.drore.eboss.login.token.TokenModel;
import com.cloud.drore.eboss.login.user.Authc;
import com.cloud.drore.eboss.login.user.CurrentUser;
import com.cloud.drore.eboss.login.user.UserAndFunction;
import com.cloud.drore.eboss.operation.entity.Merchant;
import com.cloud.drore.eboss.operation.service.IBaseDataFeign;
import com.cloud.drore.eboss.operation.service.impl.MerchantServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

/**
 * 浙江卓锐科技股份有限公司 版权所有 © Copyright 2018<br>
 *
 * @Description: <br>
 * @Project: eboos <br>
 * @CreateDate: Created in 2018/3/26 10:16 <br>
 * @Author: <a href="836327318@qq.com">吴昌益</a>
 */
@Controller
@Slf4j
@Api(value = "/用户登录接口", description = "用户接口-wcy")
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    @Qualifier(value = "redisTemplate")
    public RedisTemplate redisTemplate;

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    ILoginFeign iLoginFeign;

    @Autowired
    IBaseDataFeign iBaseDataFeign;

    @Resource
    MerchantServiceImpl merchantServiceImpl;

   // @Value("${eboss.merchant.type}")
    private String MERCHANT_TYPE="MERCHANT_OPERATION";

    private static String AUTHOR_TYPE_ERROR = "商户类型验证失败，查看用户是否正确！！";

    private static String AUTHOR_TYPEID_ERROR = "当前用户无法获取商户信息，请核对后登录！！";

    private static String AUTHOR_STATUS_ERROR = "当前用户已作废！！";

    @ApiOperation(value = "跳转到用户登录界面")
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String loginForm(Model model) {
        log.info("--info--");
        log.debug("--debug--");
        model.addAttribute("user", new ShiroUser());
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResultMessage login(@RequestBody ShiroUser shiroUser) throws BusinessException {

        String username = shiroUser.getUsername();
        String password = shiroUser.getPassword();

        Assert.notNull(username, "username can not be empty");
        Assert.notNull(password, "password can not be empty");
        ShiroUser user = iLoginFeign.findByUsername(shiroUser);

        password = new Md5Hash(password, "www", 1024).toBase64();
        if (user == null ||  //未注册
                !user.getPassword().equals(password)) {  //密码错误
            //提示用户名或密码错误
            return ResultMessage.error(ResultCodeConstant.SERVICE_BUSSNISS_CODE,"用户名密码错误！！");
        }

        if(user != null && user.getStatus() !=1)
            throw new BusinessException(ResultCodeConstant.SERVICE_BUSSNISS_CODE,AUTHOR_STATUS_ERROR);

        if(!MERCHANT_TYPE.equals(user.getType()))
            throw new BusinessException(ResultCodeConstant.SERVICE_BUSSNISS_CODE,AUTHOR_TYPE_ERROR);

        TokenModel model = tokenManager.createToken(user.getId());
        if(user.getType().equals("MERCHANT_SUPPLIER")){
            Merchant merchant = (Merchant) merchantServiceImpl.selectByPrimaryKey(user.getTypeId());
            if(merchant==null)
                throw new BusinessException(ResultCodeConstant.SERVICE_BUSSNISS_CODE,AUTHOR_TYPEID_ERROR);
            else
                model.setMerchantName(merchant.getMerchantName());
        }

        //生成一个token，保存用户登录状态
        model.setEbossRoleRightRelation(user.getRightList());
        model.setShowImge(user.getShowImge());
        model.setIsAdmin(user.getIsAdmin());
        stringRedisTemplate.opsForValue().set(CommonConstant.CURRENT_USER_ID+user.getId(), JSONObject.toJSONString(user));
        return ResultMessage.success(model);
    }

    @ApiOperation(value = "一键登录")
    @RequestMapping(value = "admin/onekey", method = RequestMethod.GET)
    public @ResponseBody ResultMessage getUsers(String username){
        ShiroUser user = iLoginFeign.findByUsername(new ShiroUser(username,""));
        TokenModel model = tokenManager.createToken(user.getId());
        stringRedisTemplate.opsForValue().set(CommonConstant.CURRENT_USER_ID+user.getId(), JSONObject.toJSONString(user));
        return ResultMessage.success("auth_login="+user.getId()+"_"+model.getToken());
    }

    @RequestMapping(value = "/admin/logout", method = RequestMethod.GET)
    @Authc
    @ResponseBody
    public ResultMessage logout() {
        try {
            UserInfo user = LocalData.getCurrentUser();
            tokenManager.deleteToken(user.getId());
        }catch (Exception ex){

        }
        return ResultMessage.success("退出成功");
    }

    @RequestMapping(value = "/admin/editUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑用户")
    public ResultMessage editUser(@RequestBody ShiroUser shiroUser) {

        iLoginFeign.editUser(shiroUser);

        return ResultMessage.success("修改成功");
    }

    @RequestMapping(value = "/admin/addUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加用户用户")
    public ResultMessage addUser(@RequestBody @Valid ShiroUser shiroUser) {

        ResultMessage resultMessage = iLoginFeign.addUser(shiroUser);

        return resultMessage;
    }

    @RequestMapping(value = "/admin/addUserAndRight", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "系统管理添加用户和权限")
    public ResultMessage addUserAndRight(@RequestBody UserAndFunction userAndFunction) {
        UserInfo user = LocalData.getCurrentUser();
        ShiroUser saveUser = userAndFunction.getShiroUser();
        saveUser.setTypeIndustry(user.getTypeIndustry());
        saveUser.setType(user.getType());
        saveUser.setTypeId(user.getTypeId());
        ResultMessage resultMessage = iLoginFeign.addUserAndRight(userAndFunction);
        return resultMessage;
    }

    @RequestMapping(value = "/admin/updateUserAndRight", method = RequestMethod.PUT)
    @ResponseBody
    @ApiOperation(value = "系统管理修改用户")
    public ResultMessage updateUserAndRight(@RequestBody @Valid UserAndFunction userAndFunction) {
        UserInfo user = LocalData.getCurrentUser();
        ShiroUser saveUser = userAndFunction.getShiroUser();
        saveUser.setTypeIndustry(user.getTypeIndustry());
        saveUser.setType(user.getType());
        saveUser.setTypeId(user.getTypeId());
        ResultMessage resultMessage = iLoginFeign.updateUserAndRight(userAndFunction);
        return resultMessage;
    }

    @RequestMapping(value = "/admin/function_list", method = RequestMethod.GET)
    @ApiOperation(value = "新增用户下的权限设置列表")
    public @ResponseBody ResultMessage functionList() {
        UserInfo shiroUser = LocalData.getCurrentUser();
        String type = shiroUser.getType();
        ResultMessage resultMessage = iLoginFeign.findFunctionManagerList(type);
        return resultMessage;
    }

    @ApiOperation(value = "修改密码")
    @RequestMapping(value = "admin/user/password", method = RequestMethod.POST)
    public @ResponseBody ResultMessage password(@RequestBody PasswordReset passwordReset){
        return iLoginFeign.password(passwordReset);
    }

    @ApiOperation(value = "获取用户信息")
    @RequestMapping(value = "admin/user/{id}", method = RequestMethod.GET)
    public @ResponseBody ResultMessage getUser(@PathVariable("id") Long id){
        ShiroUserVo shiroUserVo = iLoginFeign.findById(id);

        Dictionary type = iBaseDataFeign.getDictionary(shiroUserVo.getType());
        if(type!=null)
            shiroUserVo.setType(iBaseDataFeign.getDictionary(shiroUserVo.getType()).getName());
        Dictionary typeindustry = iBaseDataFeign.getDictionary(shiroUserVo.getTypeIndustry());
        if(typeindustry!=null)
            shiroUserVo.setTypeIndustry(iBaseDataFeign.getDictionary(shiroUserVo.getTypeIndustry()).getName());
        return ResultMessage.success(shiroUserVo);
    }

    @ApiOperation(value = "获取用户列表")
    @RequestMapping(value = "admin/getUsers", method = RequestMethod.GET)
    public @ResponseBody ResultMessage getUsers(){
        UserInfo shiroUser = LocalData.getCurrentUser();
        return iLoginFeign.findUserList(shiroUser.getType(), shiroUser.getTypeId());
    }

    @ApiOperation(value = "通过用户id获取用户信息和权限信息")
    @RequestMapping(value = "admin/user_function/{id}", method = RequestMethod.GET)
    public @ResponseBody ResultMessage<UserAndFunction> getUserFunction(@PathVariable("id") Long id){
        return ResultMessage.success(iLoginFeign.findUserFunctionById(id));
    }

    @ApiOperation(value = "重置密码")
    @RequestMapping(value = "/admin/resetPassword/{id}", method = RequestMethod.GET)
    public @ResponseBody ResultMessage resetPassword(@PathVariable("id") Long id){
        return iLoginFeign.resetPassword(id);
    }

    @ApiOperation(value = "设置用户状态1正常状态，2作废状态")
    @RequestMapping(value = "/admin/resetUserStatus/{id}/{status}", method = RequestMethod.GET)
    public @ResponseBody ResultMessage resetPassword(@PathVariable("id") Long id, @PathVariable("status") int status){
        return iLoginFeign.disableUser(id, status);
    }

}
